<template>
  <v-chart
    :ref='chartOption.refID'
    :theme='tdTheme'
    :autoresize='true'
    @click='onClick'
    :options='polar'
  />
</template>

<script>
import 'echarts'
import ECharts from 'vue-echarts'
import tdTheme from './theme.json'
import chartMixins from './chartMixins'

export default {
  name: 'ChartPie',
  components: {
    'v-chart': ECharts
  },
  mixins: [chartMixins],
  props: {},
  data() {
    return {
      tdTheme: tdTheme,
      polar: {},
      chartOption: {
        bottom: {
          type: Number,
          default: 50
        },
        series: Array,
        refID: String,
        text: String,
        subText: String,
        seriesColorFn: Function
      }
    }
  },
  methods: {
    init() {
      let legend
      let seriesData
      if (this.chartOption && this.chartOption.series && this.chartOption.series.map) {
        legend = this.chartOption.series.map(_ => _.name)
        seriesData = this.chartOption.series.map(_ => {
          return {
            name: _.name,
            value: _.data[0]
          }
        })
        const seriesData_start = {
          name: '',
          value: seriesData.reduce((acc, cur) => {
            acc += parseFloat(cur.value)
            return acc
          }, 0),
          itemStyle: {
            normal: {
              color: 'rgba(80,150,224,0)'
            }
          }

        }
        window['seriesData_start'] = seriesData_start
        seriesData.unshift(seriesData_start)
      }
      let option = {
        // toolbox: {// 工具栏,内置有导出图片，数据视图，动态类型切换，数据区域缩放，重置五个工具。
        //   orient: 'vertical',
        //   feature: {// 各工具配置项。
        //     dataView: {// 数据视图工具，可以展现当前图表所用的数据，编辑后可以动态更新。
        //       show: false, // 是否显示组件。
        //       readOnly: false
        //     },
        //     magicType: {// 动态类型切换 示例：feature: { magicType: {type: ['line', 'bar', 'stack', 'tiled']}}
        //       show: true,
        //       type: ['line', 'bar', 'stack', 'tiled']
        //     },
        //     restore: {// 配置项还原。
        //       show: true
        //     },
        //     saveAsImage: {// 保存为图片。
        //       show: true
        //     }
        //   }
        // },
        title: {
          text: this.chartOption.text,
          subtext: this.chartOption.subText,
          x: 'center',
          y: 'center',
          textStyle: {
            color: '#fff',
            fontSize: '10px',
            fontWeight: '600'
          }
        },
        tooltip: {
          trigger: 'item',
          // formatter: '{a} <br/>{b} : {c} ({d}%)'
          // formatter: '{b} : {c} ({d}%)',
          formatter: evt => {
            return `${evt.name}：${evt.value}（${((parseFloat(evt.value) / seriesData_start.value)*100).toFixed(2)}%）`
          },
          position: function(point) {
            return [point[1] - 30, -10]
          }
        },
        legend: {
          top: 20,
          bottom: 20,
          right: '10%',
          data: legend,
          show: this.chartOption && this.chartOption.leged && this.chartOption.leged.show
        },
        grid: {
          top: 120,
          bottom: -150,
          left: '10%',
          right: '10%'
        },
        series: [
          {
            type: 'pie',
            startAngle: 0,
            radius: ['60%', '100%'],
            center: ['50%', '90%'],
            hoverOffset: 2,
            data: seriesData,
            label: {
              color:'#ffffff',
              show: true,
              position: 'outside',
              formatter: (evt) => {
                console.log('evt', evt)
                if (evt.name !== '') {
                  return `${evt.name}：${((parseFloat(evt.value) / seriesData_start.value)*100).toFixed(2)}%`
                } else {
                  return ''
                }
              }
            },
            itemStyle: {
              color: this.chartOption.seriesColorFn,
              borderWidth: 0,
              borderColor: '#1C4159'
            },
            emphasis: {
              shadowBlur: 3,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        ]
      }
      // console.log('half pie option', JSON.stringify(option))
      this.polar = option
      // console.log('option=>', JSON.stringify(option))
    },
    onClick(event, instance, echarts) {
      console.log(event, instance, echarts)
      this.$emit('chartClick', arguments)
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.init()
    })
  }
}
</script>
<style scoped>
.echarts {
  width: 100%;
  height: 100%;
}
</style>
